package young.dom4j;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.util.StringUtils;
import org.xml.sax.SAXException;

import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

/**
 * Xml文件读取测试
 *
 * @author ：<a href="mailto:youngkun2016@163.com">young</a>
 * @date ：Created in 2021/7/19
 */
public class XmlReaderTest {

    public static void main(String[] args) throws SAXException, DocumentException {
        XmlReaderTest t = new XmlReaderTest();
        SAXReader saxReader = new SAXReader();
        // 读取文件
        Document read = saxReader.read(t.getClassPath("form.xml"));
        // 获取根节点
        Element rootElement = read.getRootElement();
        t.getNodes(rootElement);
    }

    /**
     * 1. 通过文件名获取输入流
     *
     * @param xmlPath
     * @return
     */
    public InputStream getClassPath(String xmlPath) {
        InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(xmlPath);
        return resourceAsStream;
    }

    /**
     * 2. 获取节点信息
     *
     * @param rootElement
     */
    public void getNodes(Element rootElement) {
        System.out.println("获取当前名称:" + rootElement.getName());
        // 获取属性信息
        List<Attribute> attributes = rootElement.attributes();
        for (Attribute attribute : attributes) {
            System.out.println("属性:" + attribute.getName() + " : " + attribute.getText());
        }
        // 获取属性value
        String value = rootElement.getTextTrim();
        if (!StringUtils.isEmpty(value)) {
            System.out.println("value:" + value);
        }
        // 使用迭代器遍历,继续遍历子节点
        Iterator<Element> elementIterator = rootElement.elementIterator();
        while (elementIterator.hasNext()) {
            Element next = elementIterator.next();
            getNodes(next);
        }
    }
}
